<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/3/31 11:15
 */

namespace App\Controller\User;


use App\Controller\ApiController;
use App\Request\Auth\UserBindAccountRequest;
use App\Request\Auth\UserLoginRequest;
use App\Request\Auth\UserRegisterRequest;
use App\Request\Mini\WxMiniAuthLoginRequest;
use App\Service\User\AuthService;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Config\config;

class AuthController extends ApiController
{


    #[Inject]
    protected AuthService $authService;

    /**
     * 账号登录
     * @param UserLoginRequest $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function login(UserLoginRequest $request)
    {
        $data = $request->validated();
        list($token,$userInfo) = $this->authService->login($data['account'],$data['password']);
        return $this->responseOk([
            'token' => $token,
            'userInfo' => $userInfo,
            'token_type'    => 'Bearer',
            'expires_in'    => time() + config('auth.guards.sso.ttl'),
        ],'登录成功');
    }

    public function wxCodeAuth(WxMiniAuthLoginRequest $request)
    {
        $data = $request->validated();

        $softId = $data['soft_id'] ?? 0;
        $accountId = $data['account_id'] ?? 0;
        list($token,$userInfo) = $this->authService->wxCodeLogin($data['code'],$softId,$accountId);

        return $this->responseOk([
            'token' => $token,
            'userInfo' => $userInfo,
            'token_type'    => 'Bearer',
            'expires_in'    => time() + config('auth.guards.sso.ttl'),
        ],'登录成功');
    }


    public function register(UserRegisterRequest $request)
    {
        $data = $request->validated();

        $this->authService->register($data);

        return $this->responseOk([],"注册成功");
    }


    public function logOut()
    {
        $this->authService->loginOut();
        return $this->responseOk([],"退出成功");
    }

    public function bindUser(UserBindAccountRequest $request)
    {
        $data = $request->validated();

        list($token,$userInfo) = $this->authService->bindUidAccount($data);

        return $this->responseOk([
            'token' => $token,
            'userInfo' => $userInfo,
            'token_type'    => 'Bearer',
            'expires_in'    => time() + config('auth.guards.sso.ttl'),
        ],'登录成功');
    }
}